import { memo, useRef, useState } from "react";
import { HeaderWapper, SearchAreaWrapper } from "./style";
import IconLogo from "@/assets/svg/icon_logo";
import classNames from "classnames";
import { useSelector, shallowEqual } from "react-redux";
import { useNavigate } from "react-router-dom";
import HeaderRight from "./comps/right";
import HeaderCenter from "./comps/center";
import { ThemeProvider } from "styled-components";
import useScrollPosition from "@/hooks/useScrollPosition";

const Header = memo(() => {
  const [isSearch, setIsSearch] = useState(false);
  const { headerConfig } = useSelector((state) => state.main, shallowEqual);
  const navigate = useNavigate();
  const prevScrollY = useRef(0);
  const { scrollY } = useScrollPosition();

  if (!isSearch) prevScrollY.current = scrollY;
  if (isSearch && Math.abs(scrollY - prevScrollY.current) > 30) setIsSearch(false);

  const isAlpha = headerConfig.topAlpha && scrollY === 0;

  return (
    <ThemeProvider theme={{ isAlpha }}>
      <HeaderWapper isAlpha={isAlpha} className={classNames({ fixed: headerConfig.isFixed })}>
        <div className="content">
          <div className="top">
            <div className="left">
              <div className="logo" onClick={() => navigate("/home")}>
                <IconLogo></IconLogo>
              </div>
            </div>
            <HeaderCenter isSearch={isAlpha || isSearch} searchBarClick={(e) => setIsSearch(true)} />
            <HeaderRight></HeaderRight>
          </div>
          <SearchAreaWrapper isSearch={isAlpha || isSearch} />
        </div>
        {isSearch && <div className="cover" onClick={(e) => setIsSearch(false)}></div>}
      </HeaderWapper>
    </ThemeProvider>
  );
});

export default Header;
